﻿namespace Dissemination.MVC.Controllers
{
    using System.Web.Mvc;
    using Repositories;
    using Models;

    using ViewModels;
    using System;
    using System.Linq;
    using Dissemination.MVC.Controllers.Extensions;
    using System.Collections.Generic;

    [HandleError]
    public class FollowUpController : ControllerBase
    {
        protected FollowUpRepository Repository = new FollowUpRepository();

        #region List

        //
        // GET: /Assessment?SeminarID=5

        /// <summary>
        /// Returns the view associated to the list of entities in the data source.
        /// </summary>
        /// <param name="seminarID"></param>
        /// <returns>Index view</returns>
        [Authorize(Roles = "Demostrator,Administrator,Reporter")]
        public ActionResult Index(int seminarID)
        {
            if (log.IsDebugEnabled) log.Debug("Entering FollowUps list...");
            FollowUpListViewModel model = new FollowUpListViewModel();
            model.FollowUps = Repository.ListBySeminarID(seminarID);
            model.ParticipantsCount = Repository.GetSeminarByID(seminarID).Participants.Count;
            if (log.IsDebugEnabled) log.Debug("Leaving FollowUps list...");
            return View(model);
        }

        #endregion

        #region Details

        //
        // GET: /Assessment/Details/5

        /// <summary>
        /// Returns the view associated to the details of an entity in the data source.
        /// </summary>
        /// <param name="id">The entity id.</param>
        /// <returns>Details view</returns>
        [Authorize(Roles = "Demostrator,Administrator,Reporter")]
        public ActionResult Details(int id)
        {
            if (log.IsDebugEnabled) log.DebugFormat("Entering FollowUp details with id={0}...", id); 
            FollowUp followUp = Repository.Get(id);

            if (log.IsDebugEnabled) log.DebugFormat("Leaving FollowUp details with id={0}...", id); 
            return followUp == null ? this.View("NotFound") : this.View(followUp);
        }

        #endregion

        #region New

        //
        // GET: /Assessment/Create?SeminarID=5

        /// <summary>
        ///  Creates the specified entity.
        /// </summary>
        /// <param name="seminarID">The entity</param>
        /// <returns>Details view</returns>
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Create(int seminarID)
        {
            if (log.IsDebugEnabled) log.Debug("Entering FollowUp creation (POST)..."); 
            Seminar seminar = Repository.GetSeminarByID(seminarID);

            if (seminar.Participants.Count <= seminar.FollowUps.Count)
            {
                ApplicationException exception = new ApplicationException(string.Format("The number of follow ups has reached the number of participants: ({0})", seminar.Participants.Count));
                if (log.IsErrorEnabled) log.Error(exception);
                return this.View("Error", exception);
            }
            var viewModel = new FollowUpViewModel
            {
                FollowUp = new FollowUp(),
                Genders = Repository.GetGendersList(),
                ProfessionalBackgrounds = Repository.ListProfessionalBackgrounds(),
                Specialities = Repository.ListSpecialities(),
                Roles = Repository.GetRoles(),
                Attitude = Repository.GetAttitudes(),
                Confident = Repository.GetOptions(5),
            };
            
            if (log.IsDebugEnabled) log.Debug("Leaving FollowUp creation (POST)..."); 
            return this.View(viewModel);
        }

        //
        // POST: /TargetArea/Create

        [HttpPost]
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Create(FollowUp followUp)
        {
            if (ModelState.IsValid)
            {
                var seminarID = int.Parse(RouteData.Values["seminarID"].ToString());
                followUp.Seminar = Repository.GetSeminarByID(seminarID);
                followUp.Gender = Repository.GetGenderByID(int.Parse(Request["FollowUp.FollowUpGenderID"]));
                followUp.ProfessionalBackground = Repository.GetProfessionalBackgroundByID(int.Parse(Request["FollowUp.FollowUpProfessionalBackgroundID"]));
                followUp.Speciality = Repository.GetSpecialityByID(int.Parse(Request["FollowUp.FollowUpSpecialityID"]));
                Repository.Add(followUp);
                Repository.Save();

                return RedirectToAction("Index", new { seminarID = followUp.Seminar.SeminarID });
            }

            return View(followUp);
        }

        #endregion

        //
        // GET: /TargetArea/Edit/5
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Edit(int id)
        {

            FollowUp followUp = Repository.Get(id);
            if (followUp == null)
                return View("NotFound");

            var viewModel = new FollowUpViewModel
            {
                FollowUp = followUp,
                Genders = Repository.GetGendersList(),
                ProfessionalBackgrounds = Repository.ListProfessionalBackgrounds(),
                Specialities = Repository.ListSpecialities(),
                Attitude = Repository.GetAttitudes(),
                Roles = Repository.GetRoles(),
                Confident = Repository.GetOptions(5),
            };

            return View(viewModel);
        }

        //
        // POST: /TargetArea/Edit/5

        [HttpPost]
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            FollowUp followUp = Repository.Get(id);
            try
            {
                UpdateModel(followUp, "FollowUp");

                followUp.Gender = Repository.GetGenderByID(int.Parse(collection["FollowUp.FollowUpGenderID"]));
                followUp.ProfessionalBackground = Repository.GetProfessionalBackgroundByID(int.Parse(Request["FollowUp.FollowUpProfessionalBackgroundID"]));
                followUp.Speciality = Repository.GetSpecialityByID(int.Parse(Request["FollowUp.FollowUpSpecialityID"]));
                Repository.Save();

                return RedirectToAction("Index", new { seminarID = followUp.Seminar.SeminarID });
            }
            catch
            {
                //ModelState.AddRuleViolations(FollowUp.GetRuleViolations());
                return View(followUp);
            }
        }


        //
        // GET: /Assessment/Export/5

        /// <summary>
        /// Returns the view associated with a given entity to be deleted
        /// </summary>
        /// <param name="id">The id of the existing entity</param>
        /// <returns>Delete view</returns>
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Export(int id)
        {
            var s = Repository.GetSeminarByID(id);
            var ta = s.TargetArea;
            var program = s.TargetArea.Program;

            List<ExcelSheetInformation> sheets = new List<ExcelSheetInformation>();
            List<ExcelCellChange> excelChanges = new List<ExcelCellChange>();


            excelChanges.AddRange(new List<ExcelCellChange>
                    {
                                new ExcelCellChange { Row = 2, Column = 2, Value = ta.Program.ProgramName },
                                new ExcelCellChange { Row = 3, Column = 2, Value = "FOLLOW UP - " + s.FriendlyTitle },
                                new ExcelCellChange { Row = 5, Column = 5, Value = s.FollowUps.Count },
                                new ExcelCellChange { Row = 8, Column = 3, Value = s.FollowUps.Average(fu => fu.FollowUpAge)??0 },
                                new ExcelCellChange { Row = 9, Column = 3, Value = s.FollowUps.Count(fu => fu.Gender.GenderName == "Male") },
                                new ExcelCellChange { Row = 10, Column = 3, Value = s.FollowUps.Count(fu => fu.Gender.GenderName == "Female") },
                                new ExcelCellChange { Row = 13, Column = 2, Value = s.FollowUps.Count(fu => fu.ProfessionalBackground.ProfessionalBackgroundID == 4) },
                                new ExcelCellChange { Row = 14, Column = 2, Value = s.FollowUps.Count(fu => fu.ProfessionalBackground.ProfessionalBackgroundID == 5) },
                                new ExcelCellChange { Row = 15, Column = 2, Value = s.FollowUps.Count(fu => fu.ProfessionalBackground.ProfessionalBackgroundID == 3) },
                                new ExcelCellChange { Row = 16, Column = 2, Value = s.FollowUps.Count(fu => fu.ProfessionalBackground.ProfessionalBackgroundID == 6) },
                                new ExcelCellChange { Row = 17, Column = 2, Value = s.FollowUps.Count(fu => fu.ProfessionalBackground.ProfessionalBackgroundID == 2) },
                                new ExcelCellChange { Row = 18, Column = 2, Value = s.FollowUps.Count(fu => fu.ProfessionalBackground.ProfessionalBackgroundID == 7) },
                                new ExcelCellChange { Row = 21, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 1) },
                                new ExcelCellChange { Row = 22, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 2) },
                                new ExcelCellChange { Row = 23, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 3) },
                                new ExcelCellChange { Row = 24, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 4) },
                                new ExcelCellChange { Row = 25, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 5) },
                                new ExcelCellChange { Row = 26, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 6) },
                                new ExcelCellChange { Row = 27, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 7) },
                                new ExcelCellChange { Row = 28, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 8) },
                                new ExcelCellChange { Row = 29, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 9) },
                                new ExcelCellChange { Row = 30, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 10) },
                                new ExcelCellChange { Row = 31, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 11) },
                                new ExcelCellChange { Row = 32, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 12) },
                                new ExcelCellChange { Row = 33, Column = 2, Value = s.FollowUps.Count(fu => fu.Speciality.SpecialityID == 13) },
                                new ExcelCellChange { Row = 8, Column = 7, Value = s.FollowUps.Count(fu => fu.FollowUpTakePart == 1) },
                                new ExcelCellChange { Row = 9, Column = 7, Value = s.FollowUps.Count(fu => fu.FollowUpTakePart == 2) },
                                new ExcelCellChange { Row = 10, Column = 7, Value = s.FollowUps.Count(fu => fu.FollowUpTakePart == 3) },
                                new ExcelCellChange { Row = 11, Column = 7, Value = s.FollowUps.Count(fu => fu.FollowUpTakePart == 4) },
                                new ExcelCellChange { Row = 12, Column = 7, Value = s.FollowUps.Count(fu => fu.FollowUpTakePart == 5) },
                                new ExcelCellChange { Row = 13, Column = 7, Value = s.FollowUps.Count(fu => fu.FollowUpTakePart == 6) },
                                new ExcelCellChange { Row = 17, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident1)??0 },
                                new ExcelCellChange { Row = 18, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident2)??0 },
                                new ExcelCellChange { Row = 19, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident3)??0 },
                                new ExcelCellChange { Row = 20, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident4)??0 },
                                new ExcelCellChange { Row = 21, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident5)??0 },
                                new ExcelCellChange { Row = 22, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident6)??0 },
                                new ExcelCellChange { Row = 23, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident7)??0 },
                                new ExcelCellChange { Row = 24, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident8)??0 },
                                new ExcelCellChange { Row = 25, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident9)??0 },
                                new ExcelCellChange { Row = 26, Column = 7, Value = s.FollowUps.Average(fu => fu.FollowUpConfident10)??0 }
                    });

            ExcelSheetInformation sheet = new ExcelSheetInformation() { Name = "Seminar follow-up", Changes = excelChanges };
            sheets.Add(sheet);
            var changes = sheets.AsQueryable();
            string temporaryFileName = Server.MapPath(@"~/temp/" + Guid.NewGuid() + ".xlsx");

            if (log.IsDebugEnabled) log.DebugFormat("Leaving Program with id {0} ta...", id);

            return this.Excel("EOD_Single_Seminar_Follow-up.xlsx", temporaryFileName, Server.MapPath(@"~/templates/EOD_Single_Seminar_Follow-up.xlsx"), "Seminar follow-up", changes);

        }


    }
}
